package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());
       try{
           log.info("令牌校验{}",token);
           //令牌校验
           Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
           Long empId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
           log.info("微信用户ID{}",empId);
           //向线程储存信息
           BaseContext.setCurrentId(empId);
           return true;
       }catch (Exception e){
           response.setStatus(401);
           return false;

       }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();//释放信息
    }
}
